package com.web.new12306.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.web.new12306.pojo.Admin;
/**
 * @author 蔡艳
 * Servlet implementation class adminLoginServlet
 */
@WebServlet("/adminLoginServlet")
public class adminLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public adminLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		HttpSession session=request.getSession();
		
		String adminname=request.getParameter("adminname");
		String password=request.getParameter("password");
		String code=request.getParameter("code");
		//System.out.println(adminname+password+code);

		
		Admin admin=new Admin();
		admin.setAdminName(adminname);
		admin.setPassword(password);
		admin.setCode(code);
		
		String msg=validate(admin);
		if (msg==null) {
			String code1=(String) session.getAttribute("code");
			if (!admin.getCode().equalsIgnoreCase(code1)) {
				msg = "验证码错误";
				request.setAttribute("msg", msg);
				request.getRequestDispatcher("/adminLogin.jsp").forward(request,
						response);
			}else {
				if ("admin".equals(admin.getAdminName())&&"123456".equals(admin.getPassword())) {
					request.getSession().setAttribute("admin", admin);
					request.getRequestDispatcher("/backstage.html").forward(request,response);
				}
			}
		}else {
			request.setAttribute("msg", msg);
			request.getRequestDispatcher("/adminLogin.jsp").forward(request,response);
		}
	}
	
	private String validate(Admin admin) {
		String errorMsg=null;
		if (admin.getAdminName()=="") {
			errorMsg="请输入管理员名！";
		}
		else if (admin.getPassword()=="") {
			errorMsg="请输入密码！";
		}
		else if (admin.getCode()=="") {
			errorMsg="请输入验证码！";
		}
		return errorMsg;
	}
}
